﻿using Mapster;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using System.Security.Claims;
using UsedBookTradeSystem.DBContext;
using UsedBookTradeSystem.Models;
using UsedBookTradeSystem.Models.Dtos.InputDtos;
using UsedBookTradeSystem.Models.Entity;
using UsedBookTradeSystem.Models.Enum;

namespace UsedBookTradeSystem.Controllers
{
    public class HomeController : Controller
    {
        private readonly SystemDbContext _ctx;
        public HomeController(SystemDbContext ctx)
        {
            _ctx = ctx;
        }

        [AllowAnonymous]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录功能
        /// </summary>
        /// <param name="userInput">用户DTO</param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<IActionResult> LoginAsync(UserInput userInput) 
        {
            if (string.IsNullOrWhiteSpace(userInput.Username)||string.IsNullOrWhiteSpace(userInput.Password)) 
            {
                TempData["OperateResult"] = "用户名或密码不得为空！";
                return View(nameof(Index));
            }
            User user = new() { UserName=userInput.Username,PassWord=userInput.Password };
            var userInfo = await _ctx.Users.FirstOrDefaultAsync(x => x.UserName == user.UserName && x.PasswordHash == user.PassWord);
            if (userInfo is null) 
            {
                TempData["OperateResult"] = "用户名或密码错误！";
                return View(nameof(Index));
            }
            if ((bool)userInfo.IsDisabled)
            {
                TempData["OperateResult"] = "用户已停用！请联系管理员进行恢复";
                return View(nameof(Index));
            }
            if (userInfo.IsDeleted)
            {
                TempData["OperateResult"] = "用户已停用，请重新注册！";
                return View(nameof(Index));
            }
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, userInfo.UserName),
                new Claim(ClaimTypes.Role, userInfo.Role.ToString())
            };
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
            return userInfo.Role switch
            {
                RoleEnum.User => RedirectToAction(nameof(Shop)),
                RoleEnum.Admin => RedirectToAction(nameof(Index),"Backend"),
                _ => View(nameof(Index))
            };
        }

        /// <summary>
        /// 跳转至注册页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public IActionResult Register() 
        {
            return View();
        }

        /// <summary>
        /// 注册用户功能
        /// </summary>
        /// <param name="registerUserInput">用户DTO</param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<IActionResult> RegisterAccount(RegisterUserInput registerUserInput)
        {
            if (string.IsNullOrWhiteSpace(registerUserInput.UserName) ||
                string.IsNullOrWhiteSpace(registerUserInput.PassWord) ||
                string.IsNullOrWhiteSpace(registerUserInput.ConfirmPassword) ||
                string.IsNullOrWhiteSpace(registerUserInput.Tel) ||
                registerUserInput.PassWord != registerUserInput.ConfirmPassword ||
                registerUserInput.Tel.Length != 11)
            {
                TempData["OperateResult"] = "输入不合法！";
                return View(nameof(Register));
            }
            if (!UInt64.TryParse(registerUserInput.Tel, out UInt64 n))
            {
                TempData["OperateResult"] = "请输入正确的手机号码！";
                return RedirectToAction(nameof(Index));
            }
            var CheckUser = await _ctx.Users.FirstOrDefaultAsync(x => x.UserName == registerUserInput.UserName);
            if (CheckUser is not null)
            {
                TempData["OperateResult"] = "用户名已存在！";
                return View(nameof(Register));
            }
            var NewAccount = registerUserInput.Adapt<User>();
            NewAccount.Cart = new()
            {
                User = NewAccount
            };
            _ctx.Users.Add(NewAccount);
            await _ctx.SaveChangesAsync(); 
            TempData["OperateResult"] = "注册成功！";
            return View(nameof(Index));
        }

        /// <summary>
        /// 跳转至商城页面
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = "User")]
        public async Task<IActionResult> Shop(int? CategoryId)
        {
            List<BookInfo> BookInfoList;
            if (CategoryId == null)
            {
                BookInfoList = await _ctx.BooksInfo.ToListAsync();
            }
            else 
            {
                BookInfoList = await _ctx.BooksInfo.Include(x => x.Category).Where(x => x.Category.Id == CategoryId).ToListAsync();
            }
            var CategoryList = await _ctx.BookCategories.ToListAsync();
            ViewData["CategoryList"] = CategoryList;
            ViewData["BookInfoList"] = BookInfoList;
            return View();
        }
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns>返回首页登录页视图</returns>
        [Authorize]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            TempData["OperateResult"] = "登出成功！";
            return View(nameof(Index));
        }
    }
}
